<?php

class torrentSearch {
	private $feeds = array('http://www.ezrss.it/search/index.php?show_name=%s&show_name_exact=true&date=%s&quality=&quality_exact=true&release_group=&mode=rss');
	private $cache = 3600;
	public $show_name;
	public $date;
	
	public function __construct($show_name, $date = '', $enddate = '')
	{
		$this->show_name = $show_name;
		if($enddate)
			$this->date[] = $enddate;
		$this->date[] = $date;
		//$this->cache = 3600*24;
		
		if(count($this->date) > 1)
		{
			do
			{
				$lbo = count($this->date)-2;
				$d = strftime("%Y-%m-%d", strtotime("{$this->date[$lbo]} - 1 day"));	
				if(end($this->date) != $d)
					array_insert($this->date, $d, $lbo+1);			
			}
			while(end($this->date) != $d);
		}
	}
	
	public function getResults()
	{
		$out = array();
		foreach($this->feeds as $feed)
		{
			foreach($this->date as $dat)
				$out = array_merge($out, $this->getFeed(sprintf($feed, rawurlencode($this->show_name), rawurlencode($dat))));
		}
		return $out;
	}
	
	private function getFeed($url)
	{
		$cacheName = CACHE_DIR . "feed-" . md5($url) . ".json";
		if($this->cache && file_exists($cacheName) && filemtime($cacheName) > (time()-$this->cache))
		{
			return json_decode(file_get_contents($cacheName), true);
		}
		else
		{
			$cont = getURLContent($url);
			$cont = $this->parseFeed($cont);
			if($this->cache)
				file_put_contents($cacheName, json_encode($cont));
			return $cont;
		}
	}
	
	protected function parseFeed($string)
	{
		$xml = simplexml_load_string($string,'SimpleXMLElement', LIBXML_NOCDATA);
		$out = array();
		foreach($xml->channel->item as $item)
		{
			$i = (array)$item;
			unset($i['comments'], $i['guid'], $i['category'], $i['enclosure']);
			$out[] = $i;
		}
		return $out;
	}
	
}


?>